﻿-- Get the LibTweetCraft library
local LibTweetCraft = LibStub:GetLibrary("LibTweetCraft-1.2")

-- Register the addon
local AddOn = LibTweetCraft:RegisterAutoTweetAddOn("Movement")

function AddOn:Initialize()
	-- Add the categories
	AddOn:AddCategory("Login", "Enter World of Warcraft", "Automatically tweets when your character enters World of Warcraft.", false)
	AddOn:AddCategory("Instance", "Enter or Leave Instance", "Automatically tweets when your character enters or leaves an instance.", false)
	AddOn:AddCategory("Zone", "Change Zone", "Automatically tweets when your character changes zones.", false)

	-- Register for events
	AddOn.EventHandler:RegisterEvent("PLAYER_LOGIN")
	AddOn.EventHandler:RegisterEvent("ZONE_CHANGED")
	AddOn.EventHandler:RegisterEvent("ZONE_CHANGED_INDOORS")
	AddOn.EventHandler:RegisterEvent("ZONE_CHANGED_NEW_AREA")
	AddOn.EventHandler:RegisterEvent("UPDATE_INSTANCE_INFO")
end

-- Add event handlers
function AddOn.EventHandler:PLAYER_LOGIN(...)

	-- Check whether this is the first login
	if firstLogin then
		local unitName = UnitName("player")
		local realmName = GetRealmName()
		local zone = GetZoneText()
		
		AddOn:Tweet("Login", "Entered World of Warcraft with " .. unitName .. " on " .. realmName .. ". #wow")
		firstLogin = false
	end
end

function AddOn.EventHandler:ZONE_CHANGED(...)
	AddOn.EventHandler:ZoneChanged()
end

function AddOn.EventHandler:ZONE_CHANGED_INDOORS(...)
	AddOn.EventHandler:ZoneChanged()
end

function AddOn.EventHandler:ZONE_CHANGED_NEW_AREA(...)
	AddOn.EventHandler:ZoneChanged()
end

function AddOn.EventHandler:ZoneChanged()
	local unitName = UnitName("player")
	local zone = GetZoneText()
	
	-- Check whether the current zone has really changed
	if tweetCraftOptions.CurrentZoneName ~= zone then
		AddOn:Tweet("Zone", unitName .. " is now in " .. zone .. ". #wow")
		tweetCraftOptions.CurrentZoneName = zone
	end
end

function AddOn.EventHandler:UPDATE_INSTANCE_INFO(...)
	local unitName = UnitName("player")
	local zone = GetRealZoneText()
	local inInstance, instanceType = IsInInstance()

	-- Tweet instance type and the current minimap zone when in an instance
	if inInstance and tweetCraftOptions.CurrentInstanceName ~= zone then
		AddOn:Tweet("Instance", unitName .. " entered " .. zone .. " " .. instanceType .. " instance. #wow")
		tweetCraftOptions.CurrentInstanceName = zone
	elseif not inInstance and tweetCraftOptions.CurrentInstanceName then
		AddOn:Tweet("Instance", unitName .. " left " .. tweetCraftOptions.CurrentInstanceName .. " instance. #wow")
		tweetCraftOptions.CurrentInstanceName = nil	
	end
end